package com.china.springServer.service.impl;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.x.discovery.ServiceDiscovery;
import org.apache.curator.x.discovery.ServiceDiscoveryBuilder;
import org.apache.curator.x.discovery.ServiceInstance;
import org.omg.CORBA.ServiceDetail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.net.InetAddress;

/**
 * @fileName: ApplicationRunnerImpl
 * @author: LmR
 * @createDate: 2023/10/21 20:39
 * @Desc:
 */
@Component
public class ZookeeperServerRegister implements ApplicationRunner {

    @Autowired
    private CuratorFramework curatorClient;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        InetAddress address = InetAddress.getLocalHost();

        /**
         * POJO that represents a service instance
         * 代表一个服务实例的信息
         */
        ServiceInstance<ServiceDetail> instance = ServiceInstance.<ServiceDetail>builder()
                .address(address.getHostAddress())      // ip地址
                .port(8080)         //端口号
                .name("server01")   // 服务名称
                .build();

        /**
         *
         */
        ServiceDiscovery<ServiceDetail> serviceDiscovery = ServiceDiscoveryBuilder.builder(ServiceDetail.class)
                .client(curatorClient)
                .basePath("myServer")  // 注册中心根路径, set the base path to store in ZK
                .build();

        // 服务注册
        serviceDiscovery.registerService(instance);
        serviceDiscovery.start();
    }
}
